package com.csust.automaticteach.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csust.automaticteach.model.enums.QuestionSubmitLanguageEnum;
import com.csust.automaticteach.model.enums.QuestionSubmitStatusEnum;
import com.csust.automaticteach.exception.BusinessException;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.judge.JudgeService;
import com.csust.automaticteach.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.csust.automaticteach.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.csust.automaticteach.model.entity.Question;
import com.csust.automaticteach.model.entity.QuestionSubmit;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.vo.question.QuestionSubmitVO;
import com.csust.automaticteach.service.QuestionService;
import com.csust.automaticteach.service.QuestionSubmitService;
import com.csust.automaticteach.mapper.QuestionSubmitMapper;
import com.csust.automaticteach.service.UserService;
import com.csust.automaticteach.utils.SqlUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.csust.automaticteach.constant.OrderConstant.ASC;
import static com.csust.automaticteach.constant.QuestionSubmitConstant.LANGUAGE_ERROR;
import static com.csust.automaticteach.constant.QuestionSubmitConstant.QUESTION_NOT_EXIST;

/**
* @author 钰玟
* @description 针对表【t_question_submit(题目提交)】的数据库操作Service实现
* @createDate 2025-06-05 14:20:31
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{
    @Resource
    private QuestionService questionService;
    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //1.判断语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum submitLanguageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        //  语言不存在
        if(submitLanguageEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,LANGUAGE_ERROR);
        }
        //2.判断题目是否存在
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question questionById = questionService.getById(questionId);
        if(questionById==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,  QUESTION_NOT_EXIST);
        }
        //题目串行提交
        //3.构造实体类
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(loginUser.getId());//用户Id
        questionSubmit.setQuestionId(questionId);//题目Id
        questionSubmit.setCode(questionSubmitAddRequest.getCode());//代码
        questionSubmit.setLanguage(language);//语言
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());//状态
        questionSubmit.setJudgeInfo("{}");//判题信息
        boolean save = this.save(questionSubmit);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        // 执行判题服务
        CompletableFuture.runAsync(() -> {
            //TODO 判题
            QuestionSubmit judgedQuestionSubmit = judgeService.doJudge(questionSubmitId);
        });
        return questionSubmitId;
    }
    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(ASC),
                sortField);
        return queryWrapper;
    }
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}




